import axios from 'axios';
import { store } from '../vuex/store';

// import qs from 'qs';
import { showToast} from "vant";
import Client from './common.js';

import Utils from "./Utils";



const getTokens = () => {
  let tokenObj = Client.getStore("feiyuToken");
  if(tokenObj == null) {
    return "";
  }
  return tokenObj.token;
}

axios.defaults.withCredentials = true; // 允许携带cookie
// let ApiUrl = "http://120.24.187.139:9999/"; // 线上
let ApiUrl = "http://47.120.39.237:8082"; // 线上 

// let ApiUrl = "http://localhost:8082"; // 本地 
axios.defaults.timeout = 20000;
axios.interceptors.request.use(config => {
  store.commit('showLoading');
  //在发送请求之前做某件事
  if (!(config.data instanceof FormData)) {
    if (config.method == 'post') {
      // config.data = qs.stringify(config.data);
    }
  }
  return config;
}, error => {
  store.commit('hideLoading');
  showToast("请求失败");
  return Promise.reject(error);
});
//返回状态判断(添加响应拦截器)
axios.interceptors.response.use(res => {
  if(res.data instanceof Blob) {
    store.commit('hideLoading');
    return res;
  }
  //对响应数据做些事
  store.commit('hideLoading');
  if(res.data.code == 100003) {
    Utils.delToken();
    Utils.toLogin('/login');
    return Promise.reject(res.data);
  }

  if(res.data.code != 200) {
    showToast(res.data.msg);
    return Promise.reject(res.data);
  }

  return res.data;
}, error => {
  store.commit('hideLoading');
  showToast('网络异常,请稍后再试');
  return Promise.reject(error);
});
//返回一个Promise(发送post请求)
export function fetch(urls, params={}, head = {}) {
  // getTokens()
  // return axios.post(ApiUrl + urls, params, { headers: {Authorization: getTokens()} });
  return axios.post(ApiUrl + urls, params, { headers: {token: getTokens()} });
}

export function fetchBlob(urls, params={}, head = {}) {
  return axios.post(ApiUrl + urls, params, { responseType:"blob", headers: {token: getTokens()} });
}


export function fetchGet(urls, OBJ) {
  // getTokens()
  return axios.get(ApiUrl + urls, { params: { ...OBJ }, headers: {token: getTokens()}});
}

